package com.kcl.dfss;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kcl.dfss.http.ServerConnection;
import com.kcl.dfss.utils.AppUtils;


public class LoginActivity extends Activity implements OnClickListener{

	private LinearLayout layout_login_back;
	private EditText edit_username,edit_password;
	private Button btn_login;
	private TextView text_forgetpwd;
	private String userid,braid,serid,modid,submit;
	private boolean networkState = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		
		layout_login_back = (LinearLayout) findViewById(R.id.layout_login_back);
		layout_login_back.setOnClickListener(this);
		edit_username = (EditText) findViewById(R.id.edit_username);
		edit_password = (EditText) findViewById(R.id.edit_password);
		btn_login = (Button) findViewById(R.id.btn_login);
		btn_login.setOnClickListener(this);
		text_forgetpwd = (TextView) findViewById(R.id.text_forgetpwd);
		text_forgetpwd.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_login_back:
			finish();
			break;
		case R.id.text_forgetpwd:
			startActivity(new Intent(LoginActivity.this,ForgetPasswordActivity.class));
			break;
		case R.id.btn_login:
			networkState = AppUtils.isNetworkAvailable(LoginActivity.this);
			if(networkState){
				if(edit_username.getText().toString().equals("")){
					showDialog(this, "请输入手机号");
				}else if(edit_password.getText().toString().equals("")){
					showDialog(this, "请输入密码");
				}else if(!AppUtils.isNetworkAvailable(LoginActivity.this)){
					Toast.makeText(LoginActivity.this, "无网络连接", Toast.LENGTH_SHORT).show();
				}else{
					new Thread(new Runnable() {
						
						@Override
						public void run() {
							final String phone = edit_username.getText().toString();
							final String password = edit_password.getText().toString();
							String result = ServerConnection.Login(phone, password);
							if(result.equals("exception")){
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										Toast.makeText(LoginActivity.this, "网络异常，请检查网络连接", Toast.LENGTH_SHORT).show();
									}
								});
							}else{
								try {
									final JSONObject jsonObject = new JSONObject(result);
									final String getResult = jsonObject.getString("success");
									final String msg = jsonObject.getString("msg");
									runOnUiThread(new Runnable() {
										@Override
										public void run() {
											if(getResult.equals("true")){
												String getResult2;
												try {
													getResult2 = jsonObject.getString("data");
													JSONObject object = new JSONObject(getResult2);
													userid = object.getString("userid");
													final String userpattern = object.getString("userpattern");
													final String usernick = object.getString("usernick");
													final String userhead = object.getString("userhead");
													final String md5 = object.getString("md5");
													Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
													SharedPreferences preferences = getSharedPreferences("shared_login", 0);
													preferences.edit().putBoolean("login", true).commit();
													preferences.edit().putString("userid", userid).commit();
													preferences.edit().putString("userpattern", userpattern).commit();
													preferences.edit().putString("phone", phone).commit();
													preferences.edit().putString("usernick", usernick).commit();
													preferences.edit().putString("userhead", userhead).commit();
													preferences.edit().putString("md5", md5).commit();
													preferences.edit().putString("phone", phone).commit();
													preferences.edit().putString("password", password).commit();
													
													System.out.println(userid);
													System.out.println(getResult);
													
												} catch (JSONException e) {
													// TODO Auto-generated catch block
													e.printStackTrace();
												}
												Intent intent = new Intent();
												intent.setClass(LoginActivity.this, MainActivity.class);
//											intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//											intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
												intent.putExtra("flag", 2);
												startActivity(intent);
												finish();
											}else if(getResult.equals("false")){
												Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
											}
										}
									});
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								
								//上传设备所属车型参数
								submitModel();
							}
						}
					}).start();
				}
			}else{
				Toast.makeText(LoginActivity.this, "网络连接异常，请检查网络连接", Toast.LENGTH_SHORT).show();
			}
			break;
		}
	}
	
	//信息提示对话框
	public void showDialog(final Activity context,String message){
		Dialog dialog = new AlertDialog.Builder(context)
        .setTitle("系统提示") 
        .setMessage(message) 
        .setNeutralButton("确定", 
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	dialog.dismiss();
                }
            })
        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
            }
        }).create();
    dialog.show(); 
	}
	
	public String submitModel(){
		SharedPreferences camcfg = getSharedPreferences("camcfg", 0);
		braid = camcfg.getString("braid", "");
		serid = camcfg.getString("serid", "");
		modid = camcfg.getString("modid", "");
		submit = ServerConnection.SubmitModel(braid, serid, modid, userid);
		return submit;
	}

}
